const {
	execSync
} = require('child_process');
const {
	ipcRenderer
} = require('electron');
const iconv = require('iconv-lite');
import {
	getRandomInt
} from "./tools"
// import iconv from "iconv-lite";
// import path from "path";

// let adbUrl = path.resolve("D:\\platform-tools_r34.0.4-windows\\platform-tools\\adb");
// 获取当前执行脚本的完整目录
const currentWorkingDirectory = process.cwd();
const appPath = currentWorkingDirectory;

export default {
	constructor(serial = null) {
		this.serial = serial;
	},
	sendLog(data) {
		ipcRenderer.send('message-from-renderer', data); // 向主进程发送消息
	},
	// 执行adb相关指令
	runCmd(command, args = []) {
		const cmd = appPath + `/resource/adb-tools/adb` +
			`${this.serial ? ` -s ${this.serial}` : ''} ${command} ${args.join(' ')}`;
		let result;
		console.log(cmd)
		this.sendLog(`正在执行指令v2：${cmd}`)
		result = execSync(cmd);

		return iconv.decode(result, 'cp936')
	},

	// 获取手机品牌
	getDeviceBrand() {
		return this.runCmd('shell', ['getprop', 'ro.product.brand']);
	},

	// 获取手机型号
	getDeviceType() {
		return this.runCmd('shell', ['getprop', 'ro.product.model']);
	},

	// 获取android系统版本
	async getAndroidVersion() {
		return this.runCmd('shell', ['getprop', 'ro.build.version.release']);
	},

	// 获取adb连接的设备列表
	getDeviceList() {
		const devices = this.runCmd(' devices');
		let line = devices
		line = line.split('\n');
		var res = new Array();
		if (line.length > 0) {
			for (var i = 1; i < line.length; i++) {
				if (line[i]) {
					var temp = line[i].replace(/(^\s*)|(\s*$)/g, "");
					if (temp) {

						if (line[i].split('\t')[1].indexOf("offline") != -1) {

							return "offline"

						}
						res[i - 1] = line[i].split('\t')[0];
					}
				}
			}
		}
		return res
	},

	// 安装apk文件
	async installApk(apkPath, options = {}) {
		const args = ['install'];
		if (!options.allowTestPackages) {
			args.push('-i', 'com.android.defcontainer');
		}
		if (!options.replace) {
			args.push('-r');
		}
		args.push(apkPath);
		try {
			await this.runCmd(...args);
			return true;
		} catch (error) {
			if (/INSTALL_FAILED_ALREADY_EXISTS/.test(error.message)) {
				return false;
			}
			throw error;
		}
	},

	// 卸载应用程序
	async uninstall(packageName) {
		try {
			await this.runCmd('uninstall', [packageName]);
			return true;
		} catch (error) {
			return false;
		}
	},

	// 清除应用程序缓存
	async clearCache(packageName) {
		return this.runCmd('shell', ['pm', 'clear', packageName]);
	},

	// 打开应用程序
	async openApp(app) {
		var apps = {
			'JRTT': 'com.ss.android.article.news/.activity.MainActivity',
			'FQCTFM': 'com.xs.fm.lite/com.dragon.read.pages.splash.SplashActivity',
			'FQCT': 'com.xs.fm/com.dragon.read.pages.splash.SplashActivity',
			'FQXS': 'com.dragon.read/.pages.splash.SplashActivity',
			'XGSP': 'com.ss.android.article.video/.activity.SplashActivity',
			'TTSS': 'com.ss.android.article.lite/.activity.SplashActivity',
			'DYHS': 'com.ss.android.ugc.live/com.ss.android.ugc.aweme.splash.SplashActivity',
			'DYJS': 'com.ss.android.ugc.aweme.lite/com.ss.android.ugc.aweme.splash.SplashActivity',
			'HGDJ': 'com.phoenix.read/com.dragon.read.pages.splash.SplashActivity',
			'WKLLQ': 'com.cat.readall/.activity.BrowserMainActivity',
			'KuaiShou': 'com.smile.gifmaker/com.yxcorp.gifshow.HomeActivity',
			'KSJS': 'com.kuaishou.nebula/com.yxcorp.gifshow.HomeActivity',
			'BDJS': 'com.baidu.searchbox.lite/com.baidu.searchbox.SplashActivity',
			'IQYJS': 'com.qiyi.video.lite/.homepage.HomeActivity',
			'BDDZ': 'com.baidu.searchbox.tomas/com.baidu.searchbox.SplashActivity',
			'UCJS': 'com.ucmobile.lite/com.UCMobile.main.UCMobile',
			'QMXS': 'com.kmxs.reader/com.km.app.home.view.LoadingActivity',
			'QDXS': 'com.dj.sevenRead/com.chaozh.iReader.ui.activity.WelcomeActivity'
		}
		return this.runCmd('shell', ['am', 'start', '-n', `${apps[app]}`]);
		// return this.runCmd('shell', ['am', 'start', '-n', `${packageName}/${activityName}`]);
	},
	async openApp1(app) {
		return this.runCmd('shell', ['am', 'start', '-n', `${app}`]);
		// return this.runCmd('shell', ['am', 'start', '-n', `${packageName}/${activityName}`]);
	},
	// 关闭应用程序
	async closeApp(packageName) {
		return this.runCmd('shell', ['am', 'force-stop', packageName]);
	},
	// 关闭应用程序
	async closeAllApp() {
		var arr = ['com.ss.android.article.news',
			'com.xs.fm.lite',
			'com.xs.fm',
			'com.dragon.read',
			'com.ss.android.article.video',
			'com.ss.android.article.lite',
			'com.ss.android.ugc.live',
			'com.ss.android.ugc.aweme.lite',
			'com.phoenix.read',
			'com.cat.readall',
			'com.smile.gifmaker',
			'com.kuaishou.nebula',
			'com.baidu.searchbox.lite',
			'com.qiyi.video.lite',
			'com.baidu.searchbox.tomas',
			'com.ucmobile.lite',
			'com.kmxs.reader',
			'com.dj.sevenRead'
		]
		arr.forEach(r => {
			this.runCmd('shell', ['am', 'force-stop', r]);
		})

		return
	},
	// 获取Activity
	async getActivity(packageName) {
		// exec(`adb -s ${id} shell "dumpsys window | grep mCurrentFocus"`, (error, stdout, stderr) => {
		// 	//adb shell dumpsys activity | grep mResumedActivity
		// 	//adb shell "dumpsys window | grep mCurrentFocus"
		// 	// adb -s EWS4C18905005800 shell  'dumpsys activity | grep mResumedActivity'
		// 	// adb -s 54474cc3 shell "dumpsys activity | grep mResumedActivity"
		// 	if (error) {
		// 		console.error(`执行出错: ${error}`);
		// 		return;
		// 	}
		// 	if (stderr) {
		// 		console.error(`stderr: ${stderr}`);
		// 		return;
		// 	}
		// 	var s1 = stdout.split(' ')[4].replace(/}/g, "");
		// 	console.log(s1)
		// 	// 输出当前Activity
		// 	// console.log(stdout.split(' ')[4]).substr(0, stdout.length - 1);
		// });
		return this.runCmd('shell', ['"dumpsys window | grep mCurrentFocus"']);
	},

	// 截屏
	async screenshot(filePath) {
		return this.runCmd('exec-out', ['screencap', '-p', '>', filePath]);
	},

	// 录制屏幕
	async screenRecord(filePath, options = {}) {
		const args = ['shell', 'screenrecord', filePath];
		if (options.resolution) {
			args.push('--size', options.resolution);
		}
		if (options.bitRate) {
			args.push('--bit-rate', options.bitRate);
		}
		if (options.timeLimit) {
			args.push('--time-limit', options.timeLimit);
		}
		if (options.verbose) {
			args.push('--verbose');
		}
		return this.runCmd(...args);
	},

	/*
	 模拟滑动手势
	 @param {number} startX 起始点横坐标
	 @param {number} startY 起始点纵坐标
	 @param {number} endX 终点横坐标
	 @param {number} endY 终点纵坐标
	 @param {number} duration 滑动时长（单位：毫秒）
	 @returns {Promise<void>} 返回 Promise 对象
	 */
	async swipe(startX, startY, endX, endY, duration) {
		const steps = Math.ceil(duration / 5);
		const swipeArgs = [
			"shell", "input", "swipe",
			startX, startY, endX, endY, steps
		];
		return this.exec(swipeArgs);
	},

	/*
	 模拟滑动手势2
	 @param {number} startX 起始点横坐标
	 @param {number} startY 起始点纵坐标
	 @param {number} endX 终点横坐标
	 @param {number} endY 终点纵坐标
	 @param {number} duration 滑动时长（单位：毫秒）
	 @returns {Promise<void>} 返回 Promise 对象
	 */
	async swipeS(fbl, type = 1) {
		var duration = 1000;
		var arr = fbl.split('*')
		const steps = Math.ceil(duration / 5);

		var startX = arr[0] / 2 + await getRandomInt(1, 10);
		var endX = startX + await getRandomInt(1, 10);
		if (type == 1) {
			var startY = arr[1] / 2;
			var endY = startY - 350;
		} else {
			var startY = 400;
			var endY = startY + 350;
		}

		const swipeArgs = ["input", "swipe", startX, startY, endX, endY, steps];
		return this.runCmd("shell", swipeArgs);
	},


	/*
	 模拟点击
	 @param {number} startX 起始点横坐标
	 @param {number} startY 起始点纵坐标
	 @param {number} endX 终点横坐标
	 @param {number} endY 终点纵坐标
	 @param {number} duration 滑动时长（单位：毫秒）
	 @returns {Promise<void>} 返回 Promise 对象
	 */
	async tap(startX, startY) {
		const swipeArgs = [
			"input", "tap", startX + await getRandomInt(1, 10), startY + await getRandomInt(1, 10)
		];
		return this.runCmd("shell", swipeArgs);
	},

	/*
	 模拟双击
	 @param {number} startX 起始点横坐标
	 @param {number} startY 起始点纵坐标
	 @param {number} endX 终点横坐标
	 @param {number} endY 终点纵坐标
	 @param {number} duration 滑动时长（单位：毫秒）
	 @returns {Promise<void>} 返回 Promise 对象
	 */

	async doubleTap(startX, startY) {
		const swipeArgs = [
			"input", "tap", startX + await getRandomInt(1, 10), startY + await getRandomInt(1, 10)
		];
		return this.runCmd("shell", [
			`"seq 2 | while read i;do input tap ${startX+await getRandomInt(1,10)} ${startY+await getRandomInt(1,10)} & input tap ${startX+await getRandomInt(1,10)} ${startY+await getRandomInt(1,10)}  & sleep 0.01;done"`
		]);
	},
	/*
	 回退
	 */
	async back() {
		const swipeArgs = ['input', 'keyevent', '4'];
		return this.runCmd('shell', swipeArgs);
	}
}
